package company.maestro;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class StudentListActivity extends Activity 
{
  static final private int ADD_NEW_TODO 		= Menu.FIRST;
  static final private int REMOVE_TODO 		= Menu.FIRST + 1;
  static final private int SEND_ABSENT_EMAIL 	= Menu.FIRST + 2;
  
  private static final String TEXT_ENTRY_KEY 		= "TEXT_ENTRY_KEY";
  private static final String ADDING_ITEM_KEY 	= "ADDING_ITEM_KEY";
  private static final String SELECTED_INDEX_KEY 	= "SELECTED_INDEX_KEY";
  
  // Variables to handle using Attendance vs 
  // Regular List modes.
  public static final int 	ATTENDANCE		= 1;
  public static final int 	LIST			= 2;
  public static final String	LIST_TYPE_KEY 	= "LIST_TYPE";
  public static int 			LIST_TYPE 		= LIST;
  
  private static int 			CLASS_ID		= -1;
  public static final String	CLASS_ID_KEY	= "CLASS_ID";
  
  
  public static final String IMAGE_PREFIX			= "STUDENT_ID_";
  
  private boolean addingNew = false;
  public static ArrayList<Student> students;
  
  private ArrayList<Student> absentStudents 	= new ArrayList<Student>();
  private ArrayList<Student> tardyStudents 		= new ArrayList<Student>();
  
  // UI elements for this Activity
  private ListView 			myListView;
  private EditText 			myEditText;
  private EditText 			txtGuardianName;
  private Button			myAddStudentButton;
  
  private StudentAdapter	studentAdapter;

  public static StudentDBAdapter 	database;
  Cursor 							studentListCursor;
  
  // Image handling
  private static final int REQUEST_IMAGE 		= 100; 
  private static final int ACTIVITY_CREATE 	= 0;
  
  
  /** Called when the activity is first created. */
  public void onCreate(Bundle bundle) 
  {
    super.onCreate(bundle);
    setContentView(R.layout.student_list);
    
    Bundle extras = getIntent().getExtras(); 
    
    if(extras !=null) 
    {
    	LIST_TYPE 	= extras.getInt(LIST_TYPE_KEY);
    	//LIST_TYPE = LIST;
    	CLASS_ID 	= extras.getInt(CLASS_ID_KEY);
    }

    // Initialize UI elements in this Activity
    myListView 			= (ListView)findViewById(R.id.myListView);
    myEditText 			= (EditText)findViewById(R.id.myEditText);
    myAddStudentButton 	= (Button)findViewById(R.id.myAddStudentButton);
    txtGuardianName		= (EditText)findViewById(R.id.txtGuardianName);

    // Set up the Student Adapter which is used to display
    // a row in the list.
    students 		= new ArrayList<Student>();
    int resID 		= R.layout.single_student;
    studentAdapter 	= new StudentAdapter(this, resID, students);
    
    myListView.setAdapter(studentAdapter);
    
        
    // Listener for clicks on items in the list.  When a student
    // is clicked, then display the details for this student.
    myListView.setOnItemClickListener(
            new OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> arg0, View view,
                        int position, long id) 
                {
                	if ( LIST_TYPE == LIST )
                	{
	            		// Get the item that was clicked
	                	Object o = myListView.getItemAtPosition(position);
	                	Student student = (Student)o;
	                	
	                	long studentId = student.getId();
	                	
	                	Intent intent = 
	                		new Intent(StudentListActivity.this, StudentDetailsActivity.class);
	                	intent.putExtra("STUDENT_ID", studentId);
	                	intent.putExtra("STUDENT", student);
	                	              	
						StudentListActivity.this.startActivity(intent);
                	}
                	else if ( LIST_TYPE == ATTENDANCE )
                	{
                		Log.e("StudentListActivity", "Position: " + position);
                		
                		int firstPosition = myListView.getFirstVisiblePosition(); // This is the same as child #0
                		Log.e("StudentListActivity", "First position: " + firstPosition);
                		int wantedChild = position - firstPosition;
                		

                		//position = position % 8;
                		Object o = myListView.getItemAtPosition(position);
	                	Student student = (Student)o;
	                	
	                	if ( absentStudents.contains(student) )
	                	{
	                		myListView.getChildAt(wantedChild).setBackgroundColor(Color.YELLOW);
	                		absentStudents.remove(student);
	                		tardyStudents.add(student);
	                	}
	                	else if ( tardyStudents.contains(student) )
	                	{
	                		myListView.getChildAt(wantedChild).setBackgroundColor(Color.GREEN);
	                		tardyStudents.remove(student);
	                	}
	                	else
	                	{
	                		myListView.getChildAt(wantedChild).setBackgroundColor(Color.RED);
	                		absentStudents.add(student);
	                	}
                	}
					
                	
                }
             }
         );


    registerForContextMenu(myListView);
    restoreUIState();

    database = StudentDBAdapter.getInstance(this);

    // Open or create the database
    database.open();

    populateStudentList();
    
    // Set the color based on whether this is a regular list
    // or an attendance list.
    setListColors();
  }


private void setListColors() {
	if ( LIST_TYPE == LIST )
    {
    	for ( int i = 0; i < myListView.getChildCount(); i++ )
    	{
    		myListView.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
    		myListView.getChildAt(i).setBackgroundResource(R.color.notepad_paper);
    		
    	}
    }
    else if ( LIST_TYPE == ATTENDANCE )
    {
    	for ( int i = 0; i < myListView.getChildCount(); i++ )
    	{
    		myListView.getChildAt(i).setBackgroundColor(Color.GREEN);
    	}
    }
}
  
  
  @Override
  /**
   * Called when a called Activity completes.  Currently used
   * for when the AddStudent activity returns (simply open the
   * database and populate the Student List).
   */
  protected void onActivityResult(int requestCode, int resultCode, Intent data) 
  {
      database.open();
      populateStudentList();
  }
  
 
  private void populateStudentList() 
  {
    // Get all the todo list items from the database.
    //studentListCursor = database.getAllStudentsCursor();
	long classId = -1;
	studentListCursor = database.getAllStudentsForClass(classId);
    startManagingCursor(studentListCursor);
      
    // Update the array.
    updateArray();
    stopManagingCursor(studentListCursor);
  }
  

  private void updateArray() 
  {
	  studentListCursor.requery();

	  students.clear();
	  
	  if (studentListCursor.moveToFirst())
	  {
	    do 
	    { 
	      long _id = 
	    	  studentListCursor.getLong(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_ID));
	      String _firstName = 
	    	  studentListCursor.getString(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_STUDENT_FIRST_NAME));
	      String _lastName = 
	    	  studentListCursor.getString(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_STUDENT_LAST_NAME));
	      String _guardianName = 
	    	  studentListCursor.getString(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_GUARDIAN_NAME));
	      String _guardianPhone = 
	    	  studentListCursor.getString(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_GUARDIAN_PHONE));
	      String _guardianEmail = 
	    	  studentListCursor.getString(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_GUARDIAN_EMAIL));
	      long created = 
	    	  studentListCursor.getLong(studentListCursor.getColumnIndex(StudentDBAdapter.KEY_CREATION_DATE));

	      Student student = new Student(_id, _firstName, _lastName, new Date(created));
	      student.setGuardianName(_guardianName);
	      student.setGuardianPhone(_guardianPhone);
	      student.setGuardianEmail(_guardianEmail);
	      
	      students.add(0, student);
	    } while(studentListCursor.moveToNext());
	  }
	  
	  studentAdapter.notifyDataSetChanged();
  }
  

  private void restoreUIState() 
  {
    // Get the activity preferences object.
    SharedPreferences settings = getPreferences(0);

    // Read the UI state values, specifying default values.
    String text = settings.getString(TEXT_ENTRY_KEY, "");
    Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false);

    // Restore the UI to the previous state.
    if (adding) 
    {
      addNewItem();
      myEditText.setText(text);
    }
  }
  
  
  @Override
  public void onSaveInstanceState(Bundle outState) 
  {
    outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition());

    super.onSaveInstanceState(outState);
  }
  

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) 
  {
    int pos = -1;

    if (savedInstanceState != null)
    {
      if (savedInstanceState.containsKey(SELECTED_INDEX_KEY))
      {
        pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);
      }
    }

    myListView.setSelection(pos);
  }
  
  
  @Override
  protected void onPause() 
  {
    super.onPause();
    
    // Get the activity preferences object.
    SharedPreferences uiState = getPreferences(0);
    
    // Get the preferences editor.
    SharedPreferences.Editor editor = uiState.edit();

    // Add the UI state preference values.
    editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString());
    editor.putBoolean(ADDING_ITEM_KEY, addingNew);
    
    // Commit the preferences.
    editor.commit(); 
  }
  
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) 
  {
    super.onCreateOptionsMenu(menu);
    
    if ( this.LIST_TYPE == LIST )
    {
	    // Create and add new menu items.
	    MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE,
	                                R.string.add_new);
	    MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE,
	                                R.string.remove);
	
	    // Assign icons
	    itemAdd.setIcon(R.drawable.add_new_item);
	    itemRem.setIcon(R.drawable.remove_item);
	
	    // Allocate shortcuts to each of them.
	    itemAdd.setShortcut('0', 'a');
	    itemRem.setShortcut('1', 'r');
	
	    return true;
    }
    else if ( this.LIST_TYPE == ATTENDANCE )
    {
    	MenuItem absentEmail = menu.add(0, SEND_ABSENT_EMAIL, Menu.NONE,
                "Send Email");
    	absentEmail.setShortcut('2', 'e');
    }
    return true;
  }
  

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) 
  {
    super.onPrepareOptionsMenu(menu);

    if ( this.LIST_TYPE == LIST )
    {
	    int idx = myListView.getSelectedItemPosition();
	
	    String removeTitle = getString(addingNew ? 
	                                   R.string.cancel : R.string.remove);
	
	    MenuItem removeItem = menu.findItem(REMOVE_TODO);
	    removeItem.setTitle(removeTitle);
	    removeItem.setVisible(addingNew || idx > -1);
	
	    return true;
    }
    return true;
  }
  
  
  @Override
  public void onCreateContextMenu(ContextMenu menu, 
                                  View v, 
                                  ContextMenu.ContextMenuInfo menuInfo) 
  {
    super.onCreateContextMenu(menu, v, menuInfo);

    if ( this.LIST_TYPE == LIST)
    {
    	menu.setHeaderTitle("Selected Student");
    	menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);
    }
  }
  
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) 
  {
    super.onOptionsItemSelected(item);

    int index = myListView.getSelectedItemPosition();

    switch (item.getItemId()) 
    {
      case (REMOVE_TODO): 
      {
        if (addingNew)
        {
          cancelAdd();
        } 
        else 
        {
          removeItem(index);
        }
        return true;
      }
      case (ADD_NEW_TODO): 
      { 
        addNewItem();
        return true; 
      }
      case (SEND_ABSENT_EMAIL):
      {
    	  sendAbsentEmail();
    	  return true;
      }
    }

    return false;
  }
  
  
  private void sendAbsentEmail() 
  {
	  Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
      
      emailIntent.setType("plain/text");

      // Set the email address to send to
      String sendToAddress = "";
 
      emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, 
      		new String[]{ sendToAddress });
      
      // Get today's date;
      Calendar calendar = Calendar.getInstance();
      SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");

      String todaysDate = dateFormat.format(calendar.getTime());
          

      // Set the email subject
      emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, 
      		"Absent/Late students for " + todaysDate);
      
      Collections.sort(absentStudents, new StudentLastNameComparator());
      Collections.sort(tardyStudents, new StudentLastNameComparator());
      
      String body = "";
      if ( absentStudents.size() != 0 )
      {
	      // Set the body of the email with students that were absent
	      body += "The following students were absent today: \n\n";
	      for ( Student student : absentStudents )
	      {
	    	  body += student.getLastName() + ", " + student.getFirstName() + "\n";
	      }
      }
      
      if ( tardyStudents.size() != 0 )
      {
	      body += "\n" + "The following students were tardy today: \n\n";
	      for ( Student student : tardyStudents )
	      {
	    	  body += student.getLastName() + ", " + student.getFirstName() + "\n";
	      }
      }

      // Set the email body
      emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, 
      		body);

      // Send the email
      StudentListActivity.this.startActivity(Intent.createChooser(emailIntent, 
      		"Send mail..."));
  }


@Override
  public boolean onContextItemSelected(MenuItem item) 
  {  
    super.onContextItemSelected(item);
    switch (item.getItemId()) 
    {
      case (REMOVE_TODO): 
      {
        AdapterView.AdapterContextMenuInfo menuInfo;
        menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        int index = menuInfo.position;

        removeItem(index);
        return true;
      }
    }
    return false;
  }
  
  
  @Override
  public void onDestroy() 
  {
    super.onDestroy();
    database.close();
  }
  
  
  private void cancelAdd() 
  {
    addingNew = false;
  }
  

  private void addNewItem() 
  {
	  Intent i = new Intent(this, AddStudentActivity.class);
	  startActivityForResult(i, ACTIVITY_CREATE);
  }
  

  private void removeItem(int _index) 
  {
    Student studentToRemove = students.get(_index);  
	  
    database.removeStudent(studentToRemove.getId());
    updateArray();
  }
}